package com.zhou.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhou.constant.MessageConstant;
import com.zhou.dao.PermissionMapper;
import com.zhou.entity.PageResult;
import com.zhou.entity.QueryPageBean;
import com.zhou.entity.Result;
import com.zhou.pojo.Permission;
import com.zhou.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 查询所有权限
     *
     * @return
     */
    @Override

    public List<Permission> findAll() {
        return permissionMapper.findAll();
    }

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Permission> page = permissionMapper.findByPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增权限
     *
     * @param permission
     */
    @Override
    public Result add(Permission permission) {
        //先判断权限关键字是否存在
        Permission permission1 = permissionMapper.findExist(permission);
        if (permission1 != null) {
            return new Result(false, "该权限关键字已经存在,无法创建");
        } else {
            permissionMapper.insert(permission);
            return new Result(true, MessageConstant.ADD_PERMISSION_SUCCESS);
        }
    }

    /**
     * 根据ID查询权限
     *
     * @param id
     * @return
     */
    @Override
    public Permission findById(Integer id) {
        return permissionMapper.selectByPrimaryKey(id);
    }


    /**
     * 编辑权限
     *
     * @param permission
     */
    @Override
    public void edit(Permission permission) {
        permissionMapper.updateByPrimaryKeySelective(permission);
    }

    /**
     * 根据ID删除权限
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        //判断当前权限是否已经关联到角色
        long count = permissionMapper.findCountByCheckPermissionId(id);
        if (count > 0) {
            return new Result(false, "此权限正在使用,无法删除");
        }
        permissionMapper.deleteByPrimaryKey(id);
        return new Result(true, MessageConstant.DELETE_PERMISSION_SUCCESS);
    }
}
